<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import api from '@/api'

const router = useRouter()

// 地图相关
const mapLoaded = ref(false)
const map = ref(null)
const userPosition = ref([117.155402, 31.86788]) // 默认位置：合肥
const isLocationMode = ref(false) // 是否为定位模式

// 功能模块数据
const modules = reactive([
  { id: 1, name: '低空游', icon: 'flight', desc: '畅享蓝天', color: '#4A90E2' },
  { id: 2, name: '飞行培训', icon: 'school', desc: '专业教学', color: '#0B3D91' },
  { id: 3, name: '航空展', icon: 'flag', desc: '震撼体验', color: '#4A90E2' },
  { id: 4, name: '机场接送', icon: 'logistics', desc: '便捷出行', color: '#0B3D91' },
  { id: 5, name: '航空周边', icon: 'shopping-cart', desc: '精选好物', color: '#4A90E2' },
  { id: 6, name: '航空资讯', icon: 'newspaper', desc: '实时动态', color: '#0B3D91' },
  { id: 7, name: '航空俱乐部', icon: 'friends', desc: '结交好友', color: '#4A90E2' },
  { id: 8, name: '更多服务', icon: 'apps', desc: '敬请期待', color: '#0B3D91' }
])

// 新闻列表数据
const newsList = reactive([
  {
    id: 1,
    title: '国内首个低空旅游示范区正式启动',
    time: '10分钟前',
    views: 1254,
    thumbnail: 'https://pan.feiwow.com/raw/files/17b90398-8f34-4509-952d-79cb8dbdff07-1749241617399.png'
  },
  {
    id: 2,
    title: '2023年航空产业发展趋势分析：低空经济将成为新增长点',
    time: '1小时前',
    views: 3621,
    thumbnail: 'https://pan.feiwow.com/raw/files/9f8e76e6-3aed-41e0-bb68-ac8c995abfbe-1749241924810.png'
  },
  {
    id: 3,
    title: '中空领航与多家航空公司达成战略合作，共建低空旅游生态',
    time: '3小时前',
    views: 2187,
    thumbnail: 'https://pan.feiwow.com/raw/files/0918b246-4f79-4516-b300-dd70ddbb7834-1749241488302.jpeg'
  }
])

// 内容区域状态
const contentExpanded = ref(false)
const merchantsVisible = ref(false)
const showRedPacket = ref(false) // 控制红包弹窗显示

// 商户列表数据
const merchantsList = reactive([
  {
    id: 1,
    name: '蓝天飞行俱乐部',
    description: '提供专业飞行培训、低空游览和航空体验活动',
    distance: 1200,
    image: 'https://picsum.photos/200/200?random=1'
  },
  {
    id: 2,
    name: '云端咖啡航空主题餐厅',
    description: '以航空为主题的特色餐厅，提供精美餐点和飞行模拟器体验',
    distance: 2500,
    image: 'https://picsum.photos/200/200?random=2'
  },
  {
    id: 3,
    name: '翱翔航空科技馆',
    description: '集航空知识普及、飞行体验和科技展示于一体的综合场馆',
    distance: 3800,
    image: 'https://picsum.photos/200/200?random=3'
  }
])

// 页面加载完成后初始化
onMounted(() => {
  initMap()
  loadModules()
  loadNewsList()
})

// 初始化地图
const initMap = async () => {
  try {
    // 确保高德地图API已加载
    if(window.AMap) {
      // 创建地图实例
      map.value = new AMap.Map('map-container', {
        zoom: isLocationMode.value ? 13 : 5, // 默认缩放级别
        center: userPosition.value, // 默认中心点
      });
      
      // 创建一个标记用户位置的 Marker
      const marker = new AMap.Marker({
        position: userPosition.value,
        icon: new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        }),
        offset: new AMap.Pixel(-20, -40)
      });
      
      // 将标记添加到地图
      map.value.add(marker);

      // 获取用户当前位置
      getUserLocation();
      
      // 添加一些地图标记
      addMapMarkers();

      mapLoaded.value = true;
      console.log('地图加载完成');
    } else {
      console.error('高德地图API未加载');
      Toast('地图加载失败，请刷新重试');
    }
  } catch (error) {
    console.error('地图初始化失败:', error);
    Toast('地图加载失败，请检查网络连接');
  }
};

// 获取用户当前位置
const getUserLocation = () => {
  if(window.AMap && window.AMap.Geolocation) {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位，默认:true
      timeout: 10000, // 超过10秒后停止定位，默认：5s
    });
    
    geolocation.getCurrentPosition((status, result) => {
      if(status === 'complete') {
        userPosition.value = [result.position.lng, result.position.lat];
        console.log('定位成功:', userPosition.value);
        
        // 如果是定位模式，则缩放到用户位置
        if(isLocationMode.value) {
          map.value.setZoomAndCenter(13, userPosition.value);
          
          // 生成随机红包
          generateRedPackets();
        }
      } else {
        console.log('定位失败，使用默认位置');
        // 定位失败时使用默认位置
        Toast('定位失败，已切换到默认位置');
      }
    });
  }
};

// 添加地图标记
const addMapMarkers = () => {
  // 这里可以添加全国各地的商户点位
  const markers = [
    { position: [116.397428, 39.90923], title: '北京中空航空俱乐部' },
    { position: [121.473701, 31.230416], title: '上海飞天航空体验中心' },
    { position: [114.057868, 22.543099], title: '深圳航空体验馆' },
    { position: [117.155402, 31.86788], title: '合肥航空科技馆' },
    { position: [104.065735, 30.659462], title: '成都飞行培训中心' },
    { position: [108.948024, 34.263161], title: '西安航空体验基地' }
  ];
  
  markers.forEach(item => {
    const marker = new AMap.Marker({
      position: item.position,
      title: item.title,
      icon: new AMap.Icon({
        size: new AMap.Size(40, 40),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      }),
      offset: new AMap.Pixel(-20, -40)
    });
    
    // 将标记添加到地图
    map.value.add(marker);
    
    // 添加点击事件
    marker.on('click', () => {
      Toast(item.title);
      // 显示商户列表
      merchantsVisible.value = true;
    });
  });
};

// 生成随机红包
const generateRedPackets = () => {
  if(!map.value) return;
  
  // 在用户周围随机生成3个红包
  for(let i = 0; i < 3; i++) {
    const lng = userPosition.value[0] + (Math.random() - 0.5) * 0.02;
    const lat = userPosition.value[1] + (Math.random() - 0.5) * 0.02;
    
    const marker = new AMap.Marker({
      position: [lng, lat],
      content: '<div class="red-packet-marker">🧧</div>',
      offset: new AMap.Pixel(-15, -30)
    });
    
    // 将红包标记添加到地图
    map.value.add(marker);
    
    // 添加点击事件
    marker.on('click', () => {
      // 显示红包弹窗
      showRedPacket.value = true;
      // 点击后移除红包标记
      map.value.remove(marker);
    });
  }
};

// 切换定位/全国模式
const toggleLocationMode = () => {
  isLocationMode.value = !isLocationMode.value;
  
  if(isLocationMode.value) {
    // 切换到定位模式
    getUserLocation();
    // 商户列表可见
    merchantsVisible.value = true;
  } else {
    // 切换到全国模式
    map.value.setZoomAndCenter(5, [105.0, 35.0]); // 中国中心点
    // 商户列表不可见
    merchantsVisible.value = false;
  }
};

// 加载功能模块
const loadModules = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.home.getModules()
    // modules.value = response.data
    console.log('加载功能模块')
  } catch (error) {
    console.error('加载功能模块失败:', error)
  }
}

// 加载新闻列表
const loadNewsList = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.home.getNewsList()
    // newsList.value = response.data
    console.log('加载新闻列表')
  } catch (error) {
    console.error('加载新闻列表失败:', error)
  }
}

// 处理模块点击
const handleModuleClick = (module) => {
  console.log('点击模块:', module.name)
  Toast(`您点击了${module.name}`)
  
  // 根据模块类型跳转到不同页面
  switch (module.name) {
    case '低空游':
      router.push('/airplane')
      break
    case '航空展':
      router.push('/camp')
      break
    case '航空资讯':
      router.push('/video')
      break
    default:
      Toast('功能开发中，敬请期待')
  }
}

// 处理新闻点击
const handleNewsClick = (news) => {
  console.log('点击新闻:', news.title)
  Toast(`您点击了新闻：${news.title}`)
}

// 切换内容区域展开状态
const toggleContentExpanded = () => {
  contentExpanded.value = !contentExpanded.value
}

// 处理商户点击
const handleMerchantClick = (merchant) => {
  console.log('点击商户:', merchant.name)
  Toast(`您点击了商户：${merchant.name}`)
}

// 格式化距离
const formatDistance = (distance) => {
  if (distance < 1000) {
    return `${distance}米`
  } else {
    return `${(distance / 1000).toFixed(1)}公里`
  }
}
</script>

<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="location">
        <span>中国</span>
        <van-icon name="arrow-down" />
      </div>
      <div class="search-btn" @click="() => Toast('搜索功能开发中')">
        <van-icon name="search" />
      </div>
    </div>
    
    <!-- 地图容器 -->
    <div class="map-container" id="map-container">
      <van-loading v-if="!mapLoaded" type="spinner" color="#0B3D91" />
      
      <!-- 定位/全国切换按钮 -->
      <div class="location-btn" @click="toggleLocationMode">
        <van-icon :name="isLocationMode ? 'globe-o' : 'location-o'" />
      </div>
    </div>
    
    <!-- 滑动内容区域 -->
    <div 
      class="sliding-content" 
      :class="{ 
        'expanded': contentExpanded, 
        'collapsed': !contentExpanded 
      }"
    >
      <!-- 滑动把手 -->
      <div class="sliding-handle" @click="toggleContentExpanded"></div>
      
      <!-- 八大功能模块 -->
      <div class="modules-section">
        <div class="section-title">功能服务</div>
        <div class="modules-grid">
          <div 
            v-for="module in modules" 
            :key="module.id" 
            class="module-item"
            :style="{ background: `linear-gradient(135deg, ${module.color}, #4A90E2)` }"
            @click="handleModuleClick(module)"
          >
            <div class="icon">
              <van-icon :name="module.icon" />
            </div>
            <div class="name">{{ module.name }}</div>
            <div class="desc">{{ module.desc }}</div>
          </div>
        </div>
      </div>
      
      <!-- 行业资讯 -->
      <div class="news-section">
        <div class="section-title">
          行业资讯
          <span class="more">更多</span>
        </div>
        <div class="news-list">
          <div 
            v-for="news in newsList" 
            :key="news.id" 
            class="news-item"
            @click="handleNewsClick(news)"
          >
            <div class="news-content">
              <div class="title">{{ news.title }}</div>
              <div class="meta">
                <span class="time">{{ news.time }}</span>
                <span class="views">{{ news.views }}浏览</span>
              </div>
            </div>
            <div class="thumbnail">
              <img :src="news.thumbnail" :alt="news.title">
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 商户列表 -->
    <div class="merchants-card" v-show="merchantsVisible">
      <div class="merchants-handle"></div>
      <div class="merchants-header">附近商户</div>
      <div 
        v-for="merchant in merchantsList" 
        :key="merchant.id" 
        class="merchant-item"
        @click="handleMerchantClick(merchant)"
      >
        <div class="merchant-image">
          <img :src="merchant.image" :alt="merchant.name">
        </div>
        <div class="merchant-info">
          <div class="merchant-name">{{ merchant.name }}</div>
          <div class="merchant-desc">{{ merchant.description }}</div>
          <div class="merchant-meta">
            <span class="merchant-distance">距离：{{ formatDistance(merchant.distance) }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 红包弹窗 -->
    <van-popup
      v-model="showRedPacket"
      round
      position="center"
      :style="{ width: '80%' }"
    >
      <div class="red-packet-content">
        <div class="red-packet-header">恭喜获得红包</div>
        <div class="red-packet-amount">¥8.88</div>
        <div class="red-packet-text">已存入您的账户</div>
        <van-button type="primary" block round @click="() => {Toast('红包已领取'); showRedPacket = false}">
          立即查看
        </van-button>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.home-container {
  height: 100%;
  width: 100%;
  position: relative;
  overflow: hidden;
}

/* 顶部导航栏 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: transparent;
  color: var(--dark-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  z-index: 100;
}

.navbar .location {
  display: flex;
  align-items: center;
}

.navbar .location span {
  font-size: 16px;
  font-weight: bold;
  margin-right: 5px;
}

.navbar .search-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--light-color);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

/* 地图容器 */
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background-color: #F2F3F5;
  z-index: 1;
}

/* 定位按钮 */
.location-btn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--light-color);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
  z-index: 10;
  cursor: pointer;
}

/* 滑动内容区域 */
.sliding-content {
  position: fixed;
  bottom: 60px; /* 为底部导航留出空间 */
  left: 0;
  width: 100%;
  max-height: 50%;
  overflow-y: auto;
  z-index: 10;
  padding-bottom: 10px;
  transition: max-height 0.3s ease;
  transform: translateZ(0); /* 提高性能 */
  touch-action: pan-y;
}

/* 添加滑动把手样式 */
.sliding-handle {
  width: 40px;
  height: 5px;
  border-radius: 3px;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 5px auto 10px;
  position: relative;
  z-index: 11;
}

/* 展开状态 */
.sliding-content.expanded {
  max-height: 80%;
}

/* 折叠状态 */
.sliding-content.collapsed {
  max-height: 10%;
}

/* 八大功能模块 */
.modules-section {
  margin: 10px 15px;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.modules-section .section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: var(--primary-color);
}

.modules-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.module-item {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  border-radius: 10px;
  padding: 15px 10px;
  text-align: center;
  color: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s;
}

.module-item:active {
  transform: scale(0.95);
}

.module-item .icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.module-item .name {
  font-size: 12px;
  font-weight: bold;
}

.module-item .desc {
  font-size: 10px;
  opacity: 0.8;
  margin-top: 3px;
}

/* 行业资讯 */
.news-section {
  margin: 10px 15px;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.news-section .section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: var(--primary-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.news-section .more {
  font-size: 12px;
  color: var(--secondary-color);
}

.news-list {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
}

.news-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.news-item:last-child {
  border-bottom: none;
}

.news-item .news-content {
  flex: 1;
}

.news-item .title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-item .meta {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.news-item .meta .time {
  margin-right: 10px;
}

.news-item .thumbnail {
  width: 80px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  margin-left: 10px;
}

.news-item .thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商户列表样式 */
.merchants-card {
  position: fixed;
  bottom: 60px; /* 为底部导航留出空间 */
  left: 0;
  width: 100%;
  max-height: 60%;
  overflow-y: auto;
  z-index: 10;
  padding-bottom: 10px;
  background-color: white;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
  transform: translateZ(0);
}

.merchants-handle {
  width: 40px;
  height: 5px;
  border-radius: 3px;
  background-color: rgba(0, 0, 0, 0.2);
  margin: 10px auto 5px;
}

.merchants-header {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: bold;
  color: var(--primary-color);
}

.merchant-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.merchant-image {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
}

.merchant-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.merchant-info {
  flex: 1;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.merchant-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.merchant-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.merchant-distance {
  color: var(--primary-color);
}

/* 红包弹窗样式 */
.red-packet-content {
  padding: 30px 20px;
  text-align: center;
}

.red-packet-header {
  font-size: 18px;
  font-weight: bold;
  color: var(--primary-color);
  margin-bottom: 20px;
}

.red-packet-amount {
  font-size: 36px;
  font-weight: bold;
  color: #FF3B30;
  margin-bottom: 10px;
}

.red-packet-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

/* 红包标记样式 */
.red-packet-marker {
  font-size: 24px;
  cursor: pointer;
  animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from { transform: translateY(0); }
  to { transform: translateY(-10px); }
}
</style>